﻿// ==本JS是加载Lodop插件及CLodop服务的综合示例，可直接使用，建议看懂后融进自己页面程序==
import { tplReplace } from '@/utils/template'
import { bcmul } from '@/utils/bc'

let CreatedOKLodopObject, CLodopIsLocal, CLodopJsState

// ==判断是否需要CLodop(那些不支持插件的浏览器):==
export function needCLodop() {
  try {
    const ua = navigator.userAgent
    if (ua.match(/Windows\sPhone/i)) { return true }
    if (ua.match(/iPhone|iPod|iPad/i)) { return true }
    if (ua.match(/Android/i)) { return true }
    if (ua.match(/Edge\D?\d+/i)) { return true }

    const verTrident = ua.match(/Trident\D?\d+/i)
    const verIE = ua.match(/MSIE\D?\d+/i)
    let verOPR = ua.match(/OPR\D?\d+/i)
    let verFF = ua.match(/Firefox\D?\d+/i)
    const x64 = ua.match(/x64/i)
    if ((!verTrident) && (!verIE) && (x64)) { return true } else if (verFF) {
      verFF = verFF[0].match(/\d+/)
      if ((verFF[0] >= 41) || (x64)) { return true }
    } else if (verOPR) {
      verOPR = verOPR[0].match(/\d+/)
      if (verOPR[0] >= 32) { return true }
    } else if ((!verTrident) && (!verIE)) {
      let verChrome = ua.match(/Chrome\D?\d+/i)
      if (verChrome) {
        verChrome = verChrome[0].match(/\d+/)
        if (verChrome[0] >= 41) { return true }
      }
    }
    return false
  } catch (err) {
    return true
  }
}

// ==加载引用CLodop的主JS,用双端口8000和18000(以防其中一个被占):==
function loadCLodop() {
  if (CLodopJsState === 'loading' || CLodopJsState === 'complete') return
  CLodopJsState = 'loading'
  const head = document.head || document.getElementsByTagName('head')[0] || document.documentElement
  const JS1 = document.createElement('script')
  const JS2 = document.createElement('script')
  JS1.src = 'http://localhost:8000/CLodopfuncs.js?priority=1'
  JS2.src = 'http://localhost:18000/CLodopfuncs.js'
  JS1.onload = JS2.onload = function() { CLodopJsState = 'complete' }
  JS1.onerror = JS2.onerror = function(evt) { CLodopJsState = 'complete' }
  head.insertBefore(JS1, head.firstChild)
  head.insertBefore(JS2, head.firstChild)
  CLodopIsLocal = !!((JS1.src + JS2.src).match(/\/\/localho|\/\/127.0.0./i))
}

if (needCLodop()) { loadCLodop() }// 加载

// ==获取LODOP对象主过程,判断是否安装、需否升级:==
export function lodop(oOBJECT, oEMBED) {
  const strHtmInstall = "<br><span style=\"color: #FF00FF\">打印控件未安装!点击这里<a href='install_lodop32.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</span>"
  const strHtmUpdate = "<br><span style=\"color: #FF00FF\">打印控件需要升级!点击这里<a href='install_lodop32.exe' target='_self'>执行升级</a>,升级后请重新进入。</span>"
  const strHtm64_Install = "<br><span style=\"color: #FF00FF\">打印控件未安装!点击这里<a href='install_lodop64.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</span>"
  const strHtm64_Update = "<br><span style=\"color: #FF00FF\">打印控件需要升级!点击这里<a href='install_lodop64.exe' target='_self'>执行升级</a>,升级后请重新进入。</span>"
  const strHtmFireFox = '<br><br><span style="color: #FF00FF">（注意：如曾安装过Lodop旧版附件npActiveXPLugin,请在【工具】->【附加组件】->【扩展】中先卸它）</span>'
  const strHtmChrome = '<br><br><span style="color: #FF00FF">(如果此前正常，仅因浏览器升级或重安装而出问题，需重新执行以上安装）</span>'
  const strCLodopInstall_1 = "<br><span style=\"color: #FF00FF\">Web打印服务CLodop未安装启动，点击这里<a href='CLodop_Setup_for_Win32NT.exe' target='_self'>下载执行安装</a>"
  const strCLodopInstall_2 = "<br>（若此前已安装过，可<a href='CLodop.protocol:setup' target='_self'>点这里直接再次启动</a>）"
  const strCLodopInstall_3 = '，成功后请刷新本页面。</span>'
  const strCLodopUpdate = "<br><span style=\"color: #FF00FF\">Web打印服务CLodop需升级!点击这里<a href='CLodop_Setup_for_Win32NT.exe' target='_self'>执行升级</a>,升级后请刷新页面。</span>"
  let LODOP
  try {
    const ua = navigator.userAgent
    const isIE = !!(ua.match(/MSIE/i)) || !!(ua.match(/Trident/i))
    if (needCLodop()) {
      try {
        // eslint-disable-next-line no-undef
        LODOP = getCLodop()
      } catch (err) {
        return false
      }
      if (!LODOP && CLodopJsState !== 'complete') {
        if (CLodopJsState === 'loading') alert('网页还没下载完毕，请稍等一下再操作.'); else alert('没有加载CLodop的主js，请先调用loadCLodop过程.')
        return
      }
      if (!LODOP) {
        document.body.innerHTML = strCLodopInstall_1 + (CLodopIsLocal ? strCLodopInstall_2 : '') + strCLodopInstall_3 + document.body.innerHTML
        return
      } else {
        // eslint-disable-next-line no-undef
        if (CLODOP.CVERSION < '4.1.1.4') {
          document.body.innerHTML = strCLodopUpdate + document.body.innerHTML
        }
        if (oEMBED && oEMBED.parentNode) { oEMBED.parentNode.removeChild(oEMBED) } // 清理旧版无效元素
        if (oOBJECT && oOBJECT.parentNode) { oOBJECT.parentNode.removeChild(oOBJECT) }
      }
    } else {
      const is64IE = isIE && !!(ua.match(/x64/i))
      // ==如果页面有Lodop就直接使用,否则新建:==
      if (oOBJECT || oEMBED) {
        if (isIE) { LODOP = oOBJECT } else { LODOP = oEMBED }
      } else if (!CreatedOKLodopObject) {
        LODOP = document.createElement('object')
        LODOP.setAttribute('width', 0)
        LODOP.setAttribute('height', 0)
        LODOP.setAttribute('style', 'position:absolute;left:0px;top:-100px;width:0px;height:0px;')
        if (isIE) { LODOP.setAttribute('classid', 'clsid:2105C259-1E0C-4534-8141-A753534CB4CA') } else { LODOP.setAttribute('type', 'application/x-print-lodop') }
        document.documentElement.appendChild(LODOP)
        CreatedOKLodopObject = LODOP
      } else { LODOP = CreatedOKLodopObject }
      // ==Lodop插件未安装时提示下载地址:==
      if ((!LODOP) || (!LODOP.VERSION)) {
        if (ua.indexOf('Chrome') >= 0) { document.body.innerHTML = strHtmChrome + document.body.innerHTML }
        if (ua.indexOf('Firefox') >= 0) { document.body.innerHTML = strHtmFireFox + document.body.innerHTML }
        document.body.innerHTML = (is64IE ? strHtm64_Install : strHtmInstall) + document.body.innerHTML
        return LODOP
      }
    }
    if (LODOP.VERSION < '6.2.2.6') {
      // eslint-disable-next-line no-undef
      if (!needCLodop()) { document.body.innerHTML = (is64IE ? strHtm64_Update : strHtmUpdate) + document.body.innerHTML }
    }
    // ===如下空白位置适合调用统一功能(如注册语句、语言选择等):==
    LODOP.SET_LICENSES('', '900BF099A6EFCA9543CDA37884444D505D7', '', '')
    // =======================================================
    return LODOP
  } catch (err) {
    alert('lodop出错:' + err)
  }
}

export const printLabel = (dataList, template, button = null, callback = null, printHint = true) => {
  const LODOP = lodop()
  LODOP.PRINT_INIT('标签打印')
  // 纸张设置
  let width = 210
  let height = 297
  if (template.width) {
    width = template.width
  }
  if (template.height) {
    height = template.height
  }

  LODOP.SET_PRINT_PAGESIZE(0, width + 'mm', height + 'mm', 'A4')
  // 预览窗口设置
  LODOP.SET_PREVIEW_WINDOW(0, 0, 1, width + 500, height + 900, '')
  // 设置打印机
  LODOP.SET_PRINTER_INDEXA('Gprinter  GP-3120TU')
  // 设置打印份数
  LODOP.SET_PRINT_COPIES(1)

  for (let i = 0; i < dataList.lists.length; i++) {
    // 数据内容
    let html = ''
    const params = JSON.parse(JSON.stringify(dataList.lists[i]))
    // 条码
    if (template.lists.bar_code_field && params[template.lists.bar_code_field]) {
      const code = params[template.lists.bar_code_field].toString()
      // const code = 'A2365a'
      const codeStr = parseInt(code).toString()
      let barCodeWidth = 93
      if (template.lists.bar_code_width) {
        barCodeWidth = template.lists.bar_code_width
      }
      let barCodeHeight = 25
      if (template.lists.bar_code_height) {
        barCodeHeight = template.lists.bar_code_height
      }
      let barCodeTop = 0
      if (template.lists.bar_code_top) {
        barCodeTop = template.lists.bar_code_top
      }
      let leftNum = 0
      let barCodeLeft = 50
      if (template.lists.bar_code_left) {
        barCodeLeft = template.lists.bar_code_left
        leftNum += parseFloat(barCodeLeft)
      }
      let codeTYpe = '128Auto'
      if (template.lists.fixed_left) {
        codeTYpe = template.lists.bar_code_mode
        leftNum = parseFloat(barCodeLeft)
      } else if (code.length === 4) {
        if (code !== codeStr) {
          codeTYpe = '128B'
          leftNum += 11
        } else {
          leftNum += 7
        }
      } else if (code.length === 5) {
        if (code !== codeStr) {
          codeTYpe = '128B'
          leftNum += 6
        } else {
          leftNum += 10
        }
      } else if (code.length === 6) {
        if (code !== codeStr) {
          leftNum += 21
          codeTYpe = 'EAN128B'
        } else {
          leftNum += 15
        }
      } else if (code.length === 7) {
        if (code !== codeStr) {
          leftNum += 21
          codeTYpe = '128B'
        } else {
          leftNum += 5
        }
      } else if (code.length === 8) {
        if (code !== codeStr) {
          leftNum += 18
          codeTYpe = '128B'
        } else {
          leftNum += 10
        }
      } else if (code.length === 9) {
        if (code !== codeStr) {
          leftNum += 16
          codeTYpe = '128B'
        } else {
          leftNum += 16
          codeTYpe = '128A'
        }
      } else if (code.length === 10) {
        if (code !== codeStr) {
          leftNum += 14
          codeTYpe = '128B'
        } else {
          leftNum += 14
          codeTYpe = '128A'
        }
      } else if (code.length === 11) {
        if (code !== codeStr) {
          leftNum += 11
          codeTYpe = '128B'
        } else {
          leftNum += 10
          codeTYpe = template.lists.bar_code_mode
        }
      } else if (code.length > 11) {
        codeTYpe = template.lists.bar_code_mode
      }
      if (template.lists.bar_code_mode === 'QRCode') {
        LODOP.ADD_PRINT_BARCODE(barCodeTop + 'mm', barCodeLeft + 'mm', barCodeWidth + 'mm', barCodeHeight + 'mm', 'QRCode', code)
      } else {
        LODOP.ADD_PRINT_BARCODE(barCodeTop + 'mm', leftNum, barCodeWidth, barCodeHeight, codeTYpe, code)
        LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
        // LODOP.SET_PRINT_STYLEA(0, 'Horient', 2)
        if (template.lists.rotate) {
          LODOP.SET_PRINT_STYLEA(0, 'Angle', Number(template.lists.rotate))
        }
      }
    }
    // 处理底价
    if (params.biao_qian) {
      params.biao_qian = '￥' + bcmul(params.biao_qian, 1)
    }
    // 处理成本价
    if (params.cheng_ben) {
      params.cheng_ben = '￥' + bcmul(params.cheng_ben, 1)
    }

    // 数据替换
    if (template.tfoot) {
      if (template.thead) {
        const htm = tplReplace(template.thead, params)
        const theadTop = template.lists.theadTop || 0
        const theadLeft = template.lists.theadLeft || 0
        const theadWidth = template.lists.theadWidth || 0
        const theadHeight = template.lists.theadHeight || 0
        LODOP.ADD_PRINT_HTM(theadTop, theadLeft, theadWidth, theadHeight, htm)
        LODOP.SET_PRINT_STYLEA(0, 'Angle', Number(template.lists.rotate))
      }
      if (template.tfoot) {
        const htm = tplReplace(template.tfoot, params)
        const tfootTop = template.lists.tfootTop || 0
        const tfootLeft = template.lists.tfootLeft || 0
        const tfootWidth = template.lists.tfootWidth || 0
        const tfootHeight = template.lists.tfootHeight || 0
        LODOP.ADD_PRINT_HTM(tfootTop, tfootLeft, tfootWidth, tfootHeight, htm)
        LODOP.SET_PRINT_STYLEA(0, 'Angle', Number(template.lists.rotate))
      }

      // 插入一页
      LODOP.NewPage()
    } else {
      if (template.thead) {
        html += tplReplace(template.thead, params)
      }
      // 插入数据
      LODOP.ADD_PRINT_HTM(0, 0, width + 'mm', height + 'mm', html)

      // 插入一页
      LODOP.NewPage()

      if (template.lists.rotate) {
        LODOP.SET_PRINT_STYLEA(0, 'AngleOfPageInside', Number(template.lists.rotate))
      }
    }
  }

  // 预览窗口
  if (button === 'preview') {
    // LODOP.PRINT_DESIGN()
    LODOP.PREVIEW()
  // 直接打印
  } else {
    LODOP.PRINT()
    if (printHint) {
      alert('打印命令已发送')
    }
  }

  if (callback !== null) {
    callback(true)
  } else {
    return true
  }
}
